<?php

namespace App\Recharge\Api;

use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use GuzzleHttp\Promise\PromiseInterface;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Request;

class Chongqinghaixin extends AbstractApi
{

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $data = [
            'timestamp'    => time(),
            'productId'    => $bean->getGoodsId(),
            'number'       => $bean->getAccount(),
            'num'          => $bean->getRechargeNum() * $bean->getStartCharging(), //充值数量
            'callbackUrl'  => $bean->getNotifyUrl(),
            'requestId'    => $bean->getOrderNo(),//订单号
            'checkPrice'   => $bean->getUnitPrice(),
        ];
        $array['sign'] = $this->sign($data,$bean->getSecretKey(),$bean->getSupplierNum());
        return $data;
    }
    /**
     * @param $data
     * @param $key
     * @param $user_id
     * @return string
     */
    public function sign($data,$key,$user_id): string
    {
        return md5($user_id.$key.$data['productId'].$data['requestId'].$data['num']);
    }
    /**
     * @param PendingRequest $http
     * @param InterfaceConfiguration $config
     * @param BasicInformation $bean
     * @return PromiseInterface
     */
    public function recharge(PendingRequest $http, InterfaceConfiguration $config, BasicInformation $bean): PromiseInterface
    {
        return $this->httpClient($http)->asJson()->withHeader('Authorization-User', $bean->getSupplierNum())->post($config->recharge_url, $this->rechargeData($bean));
    }

    /**
     * @inheritDoc
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('code', '');
        $order_sn = $request->input('requestId', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(in_array($status, [200, 505]))->setRechargeSuccess($status == 200);

    }

    /**
     * @param InterfaceConfiguration $config
     * @param BasicInformation $bean
     * @return array|mixed
     */
    public function balance(InterfaceConfiguration $config, BasicInformation $bean){
        $array = [
            'sign'=>md5($bean->getSupplierNum().$bean->getSecretKey())
        ];
        $curl =  httpClient()->withHeader('Authorization-User', $bean->getSupplierNum())->post($config -> balance_url, $array)->json();
        return data_get($curl, $config->balance_title, 0);
    }
}
